package com.leyou.test;

import com.leyou.common.pojo.PageResult;
import com.leyou.item.bo.SpuBo;
import com.leyou.search.LySearchServiceApplication;
import com.leyou.search.client.GoodsClient;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.ImportService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = LySearchServiceApplication.class)
public class ImportSearchDate {

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private ElasticsearchTemplate esTemplate;

    @Autowired
    private ImportService importService;

    @Autowired
    private GoodsRepository goodsRepository;

    @Test
    //创建索引的方法
    public void createIndex() {
        esTemplate.createIndex(Goods.class);
        esTemplate.putMapping(Goods.class);
    }

    @Test
    //删除索引的方法
    public void deleteGoods() {
        esTemplate.deleteIndex(Goods.class);
    }

    @Test
    //把数据导入索引库
    public void importDate() {
        Integer page = 1;
        Integer rows = 100;

        do {
            PageResult<SpuBo> result = goodsClient.querySpuByPage(page, rows, true, null, true, null);
            List<SpuBo> spus = result.getItems();

            List<Goods> goodsList=new ArrayList<>();
            spus.forEach(spu->{
                try {
                    goodsList.add(importService.buildGoods(spu));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

            goodsRepository.saveAll(goodsList);
            page++;
            rows=spus.size();
        } while (rows == 100);
    }
}
